package com.javabasic.algorithm.leetcode;

import java.util.Arrays;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see [1816. Truncate Sentence](https://leetcode-cn.com/problems/truncate-sentence/)
 * @since Created by work on 2021/12/6 11:21 下午
 */
public class TruncateSentence {

    /**
     * 暴力解法
     * @param s
     * @param k
     * @return
     */
    public String truncateSentence(String s, int k) {
        String[] split = s.split(" ");
        boolean flag = true;
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < k; i++) {
            if (flag) {
                flag = false;
                result.append(split[i]);
            } else {
                result.append(" " + split[i]);
            }
        }
        return result.toString();
    }


    public String truncateSentence2(String s, int k) {
        int len = s.length();
        String result = s;
        for (int i = 0; i < len; i++) {
            if (s.charAt(i) == ' ') {
                k--;
            }
            if (k == 0) {
                result = s.substring(0, i);
                break;
            }
        }
        return result;
    }
}
